package com.wenjie.common.unifiedReturn;

import cn.hutool.json.JSONUtil;
import com.wenjie.gateway.ResConstant;
import lombok.Data;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * @Author wenjie
 * @Date 2022/12/13
 * @Description: TODO controlle 统一返回类型
 */
@Data
public class Result<T> implements Serializable {
    private int code;
    private String errorInfo = "";
    private T data;


    public static Result success() {
        Result r = new Result<>();
        r.setCode(ResConstant.SUCCESS);
        return r;
    }

    public static void successRes() {
        Result r = new Result<>();
        r.setCode(ResConstant.SUCCESS);
        returnRes(r);
    }


    public static <T> Result<T> success(T data) {
        Result<T> r = new Result<>();
        r.setCode(ResConstant.SUCCESS);
        r.setData(data);
        return r;
    }

    public static Result fail(String errorInfo) {
        Result r = new Result<>();
        r.setCode(ResConstant.FAIL);
        r.setErrorInfo(errorInfo);
        return r;
    }

    public static void failRes(String errorInfo) {
        Result r = new Result<>();
        r.setCode(ResConstant.FAIL);
        r.setErrorInfo(errorInfo);
        returnRes(r);
    }

    public static Result create(Integer code, String errorInfo) {
        Result r = new Result<>();
        r.setCode(code);
        r.setErrorInfo(errorInfo);
        return r;
    }

    public static void createRes(Integer code, String errorInfo) {
        Result r = new Result<>();
        r.setCode(code);
        r.setErrorInfo(errorInfo);
        returnRes(r);
    }

    private static void returnRes(Result res) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            String s = JSONUtil.toJsonStr(res);
            response.getWriter().write(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void successRes(T data) {
        Result<T> r = new Result<>();
        r.setCode(ResConstant.SUCCESS);
        r.setData(data);
        returnRes(r);
    }
}
